<template>
  <div style="width: 375px;">
    <router-view v-slot="{ Component, route }">
      <keep-alive>
        <component v-if="getFirstLevelRoute(route).meta.keepAlive" :is="Component"
          :key="getFirstLevelRoute(route).name" />
      </keep-alive>
      <component v-if="!getFirstLevelRoute(route).meta.keepAlive" :is="Component" :key="getFirstLevelRoute(route).name" />
    </router-view>
  </div>
</template>

<script setup lang="js">
import { reactive, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const state = reactive({
  // 缓存缓存路由
  keepAliveList: [],
})

/**
 * 解决路由嵌套刷新的问题--获取真正的路由根结点
 * @param route
 */
const getFirstLevelRoute = (route) => {
  if (!Array.isArray(route.matched) || route.matched.length === 0) {
    return route;
  }
  return route.matched[0];
}

watch(() => route, (newValue, oldValue) => {
  console.log('>>>>> ' + newValue.name)
  if (newValue.meta.keepAlive && state.keepAliveList.indexOf(newValue.name) === -1) {
    // state.keepAliveList.push(newValue.name)
    console.log('>>>>>> ' + state.keepAliveList)
  }
}, { deep: true })
</script>

<style scoped lang="scss">
#nprogress .bar {
  background: #3CB371 !important;
}
</style>